﻿using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Navigation;
using System.Windows.Media;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using LuyenThiVer03.UserData;

namespace LuyenThiVer03
{
    public partial class PageLamBaiTracNghiem
    {
        private enum DapAn
        {
            A, B, C, D
        }
        
        public class DapAnUser
        {
            public int MaSoDapAn { get; set; }
            public bool IsDaLam;
            public bool IsPhanVan;

            public DapAnUser(int maSoDapAn)
            {
                MaSoDapAn = maSoDapAn;
                IsDaLam = false;
                IsPhanVan = false;
            }
        }

        private readonly Stopwatch _stopwatch = new Stopwatch();
        
        private string KieuThi { get; set; }
        private string ImageUrl { get; set; }
        private string MTKT_ID { get; set; }
        private int CauHoiDangLam { get; set; }
        private int TongSoCau { get; set; }
        private bool IsDangLamBai { get; set; }
        
        private const string Script = "<script type=\"text/javascript\">window.onload = function () {var elem = document.getElementById('content');window.external.Notify(elem.scrollHeight + '');}</script><div id=\"content\"><p>";
        private const string Div = "</p></div>";

        private double score;

        public PageLamBaiTracNghiem()
        {
            InitializeComponent();
            CauHoiDangLam = 1;

            var wCauHinh = new CauHinhHeThongWebService.CauHinhHeThongWebServiceSoapClient();
            wCauHinh.SelectOneCompleted += wCauHinh_OnSelectOneCompleted;
            wCauHinh.SelectOneAsync(1);
            IsDangLamBai = true;

            Touch.FrameReported += OnTouchFrameReported;            
        }

        private void OnTouchFrameReported(object sender, TouchFrameEventArgs e)
        {
            //var primaryTouchPoint = e.GetPrimaryTouchPoint(null);
            //if (primaryTouchPoint == null || primaryTouchPoint.Action != TouchAction.Move) return;
            //var tpc = e.GetTouchPoints(this);
            //if (tpc[1].Position.X > tpc[0].Position.X)
            //{
            //    MessageBox.Show("sang phai");
            //}
            //if (tpc[1].Position.X < tpc[0].Position.X)
            //{
            //    MessageBox.Show("Ssang trai");
            //}
            //if (primaryTouchPoint.Position.X < 480 && primaryTouchPoint.Position.X > 365)
            //{
            //    VisualStateManager.GoToState(this, "SettingsOpenState", true);
            //    LoadMaTranCauHoi();
            //    //ApplicationBar.IsVisible = false;
            //}
            //else if (primaryTouchPoint.Position.X > 0 && primaryTouchPoint.Position.X < 250)
            //{
            //    VisualStateManager.GoToState(this, "SettingsClosedState", true);
            //    //ApplicationBar.IsVisible = true;
            //}
            
        }

        private void OnCompositionTargetRendering(object sender, EventArgs e)
        {
            tblClock.Text = "60 : 00";
            var elapsedTime = _stopwatch.Elapsed;
            var str = string.Format("{0:D2} {1} {2:D2}", 59 - elapsedTime.Minutes, ":", 60 - elapsedTime.Seconds);
            tblClock.Text = str;
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            CauHoiDangLam = 1;
            TongSoCau = int.Parse(NavigationContext.QueryString["tongsocau"]);
            MTKT_ID = NavigationContext.QueryString["MTKT"];
            HienThiNoiDungCauHoiVaDapAn(CauHoiDangLam);

            KieuThi = NavigationContext.QueryString["kieuthi"];
            switch (KieuThi)
            {
                case "thithu":
                    _stopwatch.Start();
                    CompositionTarget.Rendering += OnCompositionTargetRendering;
                    break;
                case "onthi":
                    tblClock.Text = "ÔN THI";
                    break;
            }
        }

        private void wCauHinh_OnSelectOneCompleted(object sender, CauHinhHeThongWebService.SelectOneCompletedEventArgs e)
        {
            ImageUrl = e.Result.DuongDanWeb;
        }
        
        //giai ma + them anh cong thuc
        private string ToExtendedAscii(string html)
        {
            //string meta = "<meta name=\"viewport\" content=\"width=device-width, initial-scale=3\">";
            //chinh sua
            //sua duong dan anh
            var parse = new HtmlParse();
            html = parse.ReplacePathClientServer('/', '\\', "img", "id=noname", ImageUrl + "/" + MTKT_ID, "src", html);
            const string extendedAsciiFormat = "&#{0};";
            string encodedHtml = "";
            char[] chars = html.ToCharArray();

            foreach (char c in chars)
            {
                var ascii = Convert.ToInt32(c);
                if (ascii > 127)
                {
                    encodedHtml += string.Format(extendedAsciiFormat, ascii);
                }
                else
                {
                    encodedHtml += c;
                }
            }
            return encodedHtml;
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            var mbr = MessageBox.Show("Bạn muốn thoát?", "Thoát", MessageBoxButton.OKCancel);
            if (mbr != MessageBoxResult.OK)
            {
                e.Cancel = true;
                return;
            }
            NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
        }

        private void BtChamDiem_OnClick(object sender, RoutedEventArgs e)
        {
            if ((string) ((Button)sender).Content == "Thoát")
            {
                NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
            }
            else
            {
                var messResult = MessageBox.Show("Hãy kiểm tra lại kĩ!", "Hoàn thành?", MessageBoxButton.OKCancel);
                if (messResult == MessageBoxResult.Cancel)
                {
                    return;
                }
                _stopwatch.Stop();
                IsDangLamBai = false;
                btDapAnA.IsHitTestVisible = false;
                btDapAnB.IsHitTestVisible = false;
                btDapAnC.IsHitTestVisible = false;
                btDapAnD.IsHitTestVisible = false;
                ((ApplicationBarIconButton)ApplicationBar.Buttons[1]).IsEnabled = false;
                //pivot.SelectedItem = pivotMaTran;
                tblBaiLam.Visibility = Visibility.Collapsed;
                tblDiemSo.Visibility = Visibility.Visible;
                tblKetQua.Visibility = Visibility.Visible;
                btChamDiem.Content = "Thoát";
                BtChamDiem.Content = "Thoát";
                FillColorForOneCauHoi(CauHoiDangLam);
                LoadMaTranCauHoi();

                var kq = ChamDiem();
                int j = 0;
                for (int i = 0; i < kq.Count; i++)
                {
                    if (kq[i] == true)
                    {
                        j++;
                    }
                }               

                score = (double)j / (double)TongSoCau * 100;
                string mon = ((App)Application.Current).currentMon;
                string deso = ((App)Application.Current).deso + "";
                if (KieuThi == "thithu")
                {
                    BieuDo.saveScore(mon, new BieuDo() { Score = score, DeSo = deso });
                }
                tblDiemSo.Text = "Bạn đã đạt được " + String.Format("{0:0}",score) + " / 100 điểm.";
            }
        }

        private void BtXemBaiLam_OnClick(object sender, RoutedEventArgs e)
        {
            VisualStateManager.GoToState(this, "SettingsOpenState", true);
            LoadMaTranCauHoi();
            ApplicationBar.IsVisible = false;
        }

        //xu li button tu dong co dan
        private void WebBrowser_OnScriptNotify(object sender, NotifyEventArgs e)
        {
            var height = int.Parse(e.Value);
            var newHeight = height * 1.2;
            switch (((WebBrowser)sender).Name)
            {
                case "wbCauHoi":
                    wbCauHoi.Height = height * 0.5;
                    break;
                case "wbDapAnA":
                    wbDapAnA.Height = newHeight;
                    btDapAnA.Height = newHeight;
                    break;
                case "wbDapAnB":
                    wbDapAnB.Height = newHeight;
                    btDapAnB.Height = newHeight;
                    break;
                case "wbDapAnC":
                    wbDapAnC.Height = newHeight;
                    btDapAnC.Height = newHeight;
                    break;
                case "wbDapAnD":
                    wbDapAnD.Height = newHeight;
                    btDapAnD.Height = newHeight;
                    break;
            }
        }

        private void BtDapAn_OnClick(object sender, RoutedEventArgs e)
        {
            var userChoice = DapAn.C;
            ResetAllColorButton();
            ((Button)sender).BorderBrush = new SolidColorBrush(Colors.Orange);
            switch (((Button)sender).Name)
            {
                case "btDapAnA":
                    userChoice = DapAn.A;
                    break;
                case "btDapAnB":
                    userChoice = DapAn.B;
                    break;
                case "btDapAnC":
                    userChoice = DapAn.C;
                    break;
                case "btDapAnD":
                    userChoice = DapAn.D;
                    break;
            }
            SaveDapAn((int)userChoice);
        }

        private void BtAppBar_OnClick(object sender, EventArgs e)
        {
            ResetAllColorButton();
            switch (((ApplicationBarIconButton)sender).Text)
            {
                case "Trước":
                    CauHoiDangLam--;
                    if (CauHoiDangLam < 1)
                    {
                        CauHoiDangLam = TongSoCau;
                    }
                    HienThiNoiDungCauHoiVaDapAn(CauHoiDangLam);
                    FillColorForOneCauHoi(CauHoiDangLam);
                    scrollViewer.ScrollToVerticalOffset(0);
                    break;
                case "Đánh dấu":
                    FillColorForOneCauHoi(CauHoiDangLam);
                    if (((App)Application.Current).ListDapAnUser[CauHoiDangLam - 1].IsPhanVan)
                    {
                        ApplicationBar.BackgroundColor = Colors.Transparent;
                        ((App)Application.Current).ListDapAnUser[CauHoiDangLam - 1].IsPhanVan = false;
                    }
                    else
                    {
                        ApplicationBar.BackgroundColor = Colors.Magenta;
                        ((App)Application.Current).ListDapAnUser[CauHoiDangLam - 1].IsPhanVan = true;
                    }
                    break;
                case "Tiếp":
                    CauHoiDangLam++;
                    if (CauHoiDangLam > TongSoCau)
                    {
                        CauHoiDangLam = 1;
                    }
                    HienThiNoiDungCauHoiVaDapAn(CauHoiDangLam);
                    FillColorForOneCauHoi(CauHoiDangLam);
                    scrollViewer.ScrollToVerticalOffset(0);
                    break;
            }
        }

        private void HienThiNoiDungCauHoiVaDapAn(int cauHoi)
        {
            try
            {
                var key = ((App)Application.Current).ListKeyCauHoi[cauHoi - 1];
                wbCauHoi.NavigateToString(Script +
                                      ToExtendedAscii("<h1>Câu hỏi " + cauHoi + "</h1><br>" +
                                                      ((App)Application.Current).DicCauHoi[key]) + Div);
                wbDapAnA.NavigateToString(Script + ToExtendedAscii("A.  " + (((App)Application.Current).DicDapAn[key])[0]) + Div);
                wbDapAnB.NavigateToString(Script + ToExtendedAscii("B.  " + (((App)Application.Current).DicDapAn[key])[1]) + Div);
                wbDapAnC.NavigateToString(Script + ToExtendedAscii("C.  " + (((App)Application.Current).DicDapAn[key])[2]) + Div);
                wbDapAnD.NavigateToString(Script + ToExtendedAscii("D.  " + (((App)Application.Current).DicDapAn[key])[3]) + Div);
            }
            catch (Exception)
            {
                btDapAnA.IsHitTestVisible = false;
                btDapAnB.IsHitTestVisible = false;
                btDapAnC.IsHitTestVisible = false;
                btDapAnD.IsHitTestVisible = false;
                ((ApplicationBarIconButton)ApplicationBar.Buttons[0]).IsEnabled = false;
                ((ApplicationBarIconButton)ApplicationBar.Buttons[1]).IsEnabled = false;
                ((ApplicationBarIconButton)ApplicationBar.Buttons[2]).IsEnabled = false;
                btXemBaiLam.IsHitTestVisible = false;
                btChamDiem.IsHitTestVisible = false;
            }
        }

        private void ResetAllColorButton()
        {
            btDapAnA.BorderBrush = new SolidColorBrush(Colors.White);
            btDapAnB.BorderBrush = new SolidColorBrush(Colors.White);
            btDapAnC.BorderBrush = new SolidColorBrush(Colors.White);
            btDapAnD.BorderBrush = new SolidColorBrush(Colors.White);
        }

        private void FillColorForOneCauHoi(int cauHoi)
        {
            var dapAn = ((App)Application.Current).ListDapAnUser[cauHoi - 1].MaSoDapAn;
            FillColor(dapAn, Colors.Orange);
            if (IsDangLamBai)
            {
                ApplicationBar.BackgroundColor = ((App)Application.Current).ListDapAnUser[cauHoi - 1].IsPhanVan ? Colors.Magenta : Colors.Transparent;
            }
            else
            {
                var listKetQua = ChamDiem();
                ApplicationBar.BackgroundColor = listKetQua[cauHoi - 1] ? Colors.Red : Colors.Orange;
                var dapAnDung = ((App)Application.Current).ListDapAnDung[cauHoi - 1];
                FillColor(dapAnDung, Colors.Red);
            }
        }

        private void FillColor(int index, Color c)
        {
            switch (index)
            {
                case 0:
                    btDapAnA.BorderBrush = new SolidColorBrush(c);
                    break;
                case 1:
                    btDapAnB.BorderBrush = new SolidColorBrush(c);
                    break;
                case 2:
                    btDapAnC.BorderBrush = new SolidColorBrush(c);
                    break;
                case 3:
                    btDapAnD.BorderBrush = new SolidColorBrush(c);
                    break;
                default:
                    ResetAllColorButton();
                    break;
            }
        }

        //to mau cho 1 button o ma tran cau hoi
        private void FillColorOneButtonMaTran(int i, Button b)
        {
            if (IsDangLamBai)
            {
                if (((App)Application.Current).ListDapAnUser[i - 1].IsPhanVan)
                {
                    b.Foreground = new SolidColorBrush(Colors.Magenta);
                    b.BorderBrush = new SolidColorBrush(Colors.Magenta);
                }
                else
                {
                    if (((App)Application.Current).ListDapAnUser[i - 1].IsDaLam)
                    {
                        b.Foreground = new SolidColorBrush(Colors.Orange);
                        b.BorderBrush = new SolidColorBrush(Colors.Orange);
                    }
                    else
                    {
                        b.Foreground = new SolidColorBrush(Colors.White);
                        b.BorderBrush = new SolidColorBrush(Colors.White);
                    }
                }
            }
            else
            {
                var listKetQua = ChamDiem();
                if (listKetQua[i - 1])
                {
                    b.Foreground = new SolidColorBrush(Colors.Red);
                    b.BorderBrush = new SolidColorBrush(Colors.Red);
                }
                else
                {
                    b.Foreground = new SolidColorBrush(Colors.Orange);
                    b.BorderBrush = new SolidColorBrush(Colors.Orange);
                }
            }
        }

        private void SaveDapAn(int dapAnIdChoice)
        {
            ((App)Application.Current).ListDapAnUser[CauHoiDangLam - 1].IsDaLam = true;
            ((App)Application.Current).ListDapAnUser[CauHoiDangLam - 1].MaSoDapAn = dapAnIdChoice;
        }

        private void LoadMaTranCauHoi()
        {
            grid.Children.Clear();
            //ve button
            for (int i = 1; i <= TongSoCau; i++)
            {
                var b = new Button
                            {
                                BorderThickness = new Thickness(2),
                                Background = new SolidColorBrush(Color.FromArgb(0, 0, 0, 0)),
                                Content = i,
                                Padding = new Thickness(0,0,0,0),
                                Margin = new Thickness(0,0,0,0),
                                FontSize = 30                            
                            };
                FillColorOneButtonMaTran(i, b);
                int column;
                if (i % 5 == 0)
                {
                    column = 4;
                }
                else
                {
                    column = i % 5 - 1;
                }
                int hang;
                if (i % 5 == 0)
                {
                    hang = i / 5 - 1;
                }
                else
                {
                    hang = i / 5;
                }
                Grid.SetRow(b, hang);
                Grid.SetColumn(b, column);
                b.Click += ButtonPivotMaTran_OnClick;
                grid.Children.Add(b);
            }
        }

        private void ButtonPivotMaTran_OnClick(object sender, RoutedEventArgs e)
        {
            ResetAllColorButton();
            var b = (Button)sender;
            CauHoiDangLam = int.Parse(b.Content.ToString());
            HienThiNoiDungCauHoiVaDapAn(CauHoiDangLam);
            FillColorForOneCauHoi(CauHoiDangLam);
            VisualStateManager.GoToState(this, "SettingsClosedState", true);
            scrollViewer.ScrollToVerticalOffset(0);
            ApplicationBar.IsVisible = true;
        }

        private List<bool> ChamDiem()
        {
            return ((App)Application.Current).ListDapAnUser.Select((t, i) => t.MaSoDapAn == ((App)Application.Current).ListDapAnDung[i]).ToList();
        }
    }
}